<script setup>
import {onMounted, ref} from "vue";
import {doGet, doPost, doPut} from "../http/httpRequest.js";
import {showMessage} from "../util/utils.js";
import {useRoute, useRouter} from "vue-router";

//定义router对象
let router = useRouter(); //调对象的方法
let route = useRoute(); //点对象的属性

let clueQuery = ref({});

//验证手机号是否录入过
const checkPhone = (rule, value, callback) => {
  //判断该手机号是否已经录入过，如果已经录入过，就不能再次录入
  doGet('/api/clue/' + value, {}).then(resp => {
    if (resp.data.code === 200) {
      callback() //正常，手机号没有录入过
    } else {
      callback(new Error('该手机号已经录入过了，不能再录入'))
    }
  })
}

//表单验证规则
let clueRules = ref({
  ownerId : [
    { required: true, message: '请选择负责人', trigger: ['blur', 'change'] }
  ],
  phone : [
    { required: true, message: '手机号码不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式有误', trigger: 'blur' },
    { validator: checkPhone, trigger: 'blur' }
  ],
  fullName : [
    { pattern: /^[\u4e00-\u9fa5]+$/, message: '姓名必须是中文汉字', trigger: 'blur' }
  ],
  qq : [
    { pattern: /^\d+$/, message: 'QQ号码必须是数字', trigger: 'blur' }
  ],
  email : [
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱码格式有误', trigger: 'blur' }
  ],
  age : [
    { pattern: /^(0|[1-9][0-9]?)$|^1[0-4][0-9]$|^150$/, message: '年龄必须为0-150之间的整数', trigger: 'blur' }
  ],
  yearIncome : [
    { pattern: /^-?\d+(\.\d{1,2})?$/, message: '年收入必须是整数或者两位小数', trigger: 'blur'}
  ],
  description : [
    { min: 5, max: 255, message: '线索描述长度为5-255个字符', trigger: 'blur' }
  ]
})

//负责人的下拉列表数组对象
let ownerOptions = ref([{}])
let activityOptions = ref([{}])
let appellationOptions = ref([{}])
let needLoanOptions = ref([{}])
let intentionStateOptions = ref([{}])
let productOptions = ref([{}])
let clueStateOptions = ref([{}]);
let sourceOptions = ref([{}])

//页面的dom元素渲染后执行
onMounted(() => {
  loadOwner();
  loadActivity();
  loadProduct();
  loadDicValue('appellation');
  loadDicValue('needLoan');
  loadDicValue('intentionState');
  loadDicValue('clueState');
  loadDicValue('source');
  //根据线索id加载线索数据
  loadClue();
})

const loadOwner = () => {
  doGet('/api/user/owner', {}).then(resp => {
    if (resp.data.code === 200) {
      ownerOptions.value = resp.data.data;
    }
  })
}
const loadActivity = () => {
  doGet('/api/activity/ongoing', {}).then(resp => {
    if (resp.data.code === 200) {
      activityOptions.value = resp.data.data;
    }
  })
}

const loadProduct = () => {
  doGet('/api/product/onsale', {}).then(resp => {
    if (resp.data.code === 200) {
      productOptions.value = resp.data.data;
    }
  })
}
const loadDicValue = (typeCode) => {
  doGet('/api/dic/'+ typeCode, {}).then(resp => {
    if (resp.data.code === 200) {
      if (typeCode === 'appellation') {
        appellationOptions.value = resp.data.data.dicValueDOList;
      } else if (typeCode === 'needLoan') {
        needLoanOptions.value = resp.data.data.dicValueDOList;
      } else if (typeCode === 'intentionState') {
        intentionStateOptions.value = resp.data.data.dicValueDOList;
      } else if (typeCode === 'clueState') {
        clueStateOptions.value = resp.data.data.dicValueDOList;
      } else if (typeCode === 'source') {
        sourceOptions.value = resp.data.data.dicValueDOList;
      }
    }
  })
}

//定义form表单的ref属性对象
let clueRefForm = ref();

//录入线索（提交保存,或者是 编辑提交）
const addClueSubmit = (formEl) => {
  //验证表单
  if (!formEl) { //如果formEl不存在，也就是你没有给login()函数传userFormRef参数，那么就return，不做验证了
    return
  }
  formEl.validate((valid) => {
    if (valid) { //valid是true表示验证通过，否则没通过
      let formData = new FormData();
      for (let field in clueQuery.value) {
        if (clueQuery.value[field]) { //该字段有值，我们才放入formData中
          formData.append(field, clueQuery.value[field]);
        }
      }
      //判断是编辑还是录入
      if (clueQuery.value.id > 0) { //编辑
        doPut('/api/clue', formData).then(resp => {
          if (resp.data.code === 200) {
            showMessage('编辑成功', 'success')
            router.push('/dashboard/clue')
          } else {
            showMessage('编辑失败，原因：' + resp.data.msg, 'error');
          }
        })
      } else { //录入
        doPost('/api/clue', formData).then(resp => {
          if (resp.data.code === 200) {
            showMessage('录入成功', 'success')
            router.push('/dashboard/clue')
          } else {
            showMessage('录入失败，原因：' + resp.data.msg, 'error');
          }
        })
      }
    }
  })
}

//返回函数
const goBack = () => {
  router.back();
}

//根据id加载线索数据
const loadClue = () => {
  let clueId = route.params.clueId
  if (clueId) { //clueId存在，说明是编辑，需要查询线索数据
    doGet('/api/clue/info/' + clueId, {}).then(resp => {
      if (resp.data.code === 200) {
        clueQuery.value = resp.data.data;
      } else {
        showMessage('数据加载失败', 'error');
      }
    })
  }
}
</script>

<template>
  <el-form
      ref="clueRefForm"
      :model="clueQuery"
      :rules="clueRules"
      label-width="100px"
      style="max-width: 95%;">

    <el-form-item label="负责人" prop="ownerId">
      <el-select
          v-model="clueQuery.ownerId"
          placeholder="请选择负责人"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in ownerOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="所属活动">
      <el-select
          v-model="clueQuery.activityId"
          placeholder="请选择所属活动"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in activityOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="姓名" prop="fullName">
      <el-input v-model="clueQuery.fullName"/>
    </el-form-item>

    <el-form-item label="称呼">
      <el-select
          v-model="clueQuery.appellation"
          placeholder="请选择称呼"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in appellationOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="手机" v-if="clueQuery.id > 0"> <!--编辑-->
      <el-input v-model="clueQuery.phone" disabled/>
    </el-form-item>

    <el-form-item label="手机" prop="phone" v-else> <!--录入-->
      <el-input v-model="clueQuery.phone"/>
    </el-form-item>

    <el-form-item label="微信">
      <el-input v-model="clueQuery.weixin"/>
    </el-form-item>

    <el-form-item label="QQ" prop="qq">
      <el-input v-model="clueQuery.qq"/>
    </el-form-item>

    <el-form-item label="邮箱" prop="email">
      <el-input v-model="clueQuery.email"/>
    </el-form-item>

    <el-form-item label="年龄" prop="age">
      <el-input v-model="clueQuery.age"/>
    </el-form-item>

    <el-form-item label="职业">
      <el-input v-model="clueQuery.job"/>
    </el-form-item>

    <el-form-item label="年收入" prop="yearIncome">
      <el-input v-model="clueQuery.yearIncome"/>
    </el-form-item>

    <el-form-item label="住址">
      <el-input v-model="clueQuery.address"/>
    </el-form-item>

    <el-form-item label="贷款">
      <el-select
          v-model="clueQuery.needLoan"
          placeholder="请选择是否需要贷款"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in needLoanOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="意向状态">
      <el-select
          v-model="clueQuery.intentionState"
          placeholder="请选择意向状态"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in intentionStateOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="意向产品">
      <el-select
          v-model="clueQuery.intentionProduct"
          placeholder="请选择意向产品"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in productOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="线索状态">
      <el-select
          v-model="clueQuery.state"
          placeholder="请选择线索状态"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in clueStateOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="线索来源">
      <el-select
          v-model="clueQuery.source"
          placeholder="请选择线索来源"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in sourceOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="线索描述" prop="description">
      <el-input
          v-model="clueQuery.description"
          :rows="5"
          maxlength="255"
          show-word-limit
          type="textarea"
          placeholder="请输入线索描述"/>
    </el-form-item>

    <el-form-item label="下次联系时间">
      <el-date-picker
          v-model="clueQuery.nextContactTime"
          type="datetime"
          style="width: 100%;"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择下次联系时间"/>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="addClueSubmit(clueRefForm)">提 交</el-button>
      <el-button type="success" plain @click="goBack">返 回</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped>

</style>